<template>
  <uni-segmented-control :current="currentTagIndex" :values="tagList" @clickItem="handleTabChange" :style-type="'text'"
                         :active-color="'#dd524d'"/>
</template>
<script>
import UniSegmentedControl
  from "../../../uni_modules/uni-segmented-control/components/uni-segmented-control/uni-segmented-control.vue";
import {getAction, initDictData} from "../../../utils/action";

export default {
  name: "mySegmentedControl",
  components: {UniSegmentedControl},
  model: {
    prop: "modelValue",
    event: "update:modelValue"
  },
  props: {
    code: String,
    // 关键修复2：声明modelValue属性
    modelValue: [Number, String],
    currentIndex: [Number, String]
  },
  data() {
    return {
      tagList: [],
      currentTagIndex: 0,
      url: {
        root: "classify/rootTableList"
      }
    }
  },
  watch: {
    modelValue: {
      handler(newVal) {
        this.getData()
      },
      immediate: true // 确保初始化同步
    },
    currentIndex: {
      handler(newVal) {
        this.currentTagIndex = newVal || 0
      },
      immediate: true // 确保初始化同步
    }
  },
  mounted() {
    this.getData()
  },
  methods: {
    async getData() {
      let rel = await this.initDictData('T_dict_code_' + this.code)
      if (rel?.length) {
        this.tagList = rel;
        // 关键修复4：确保数据加载完成后再传值
        this.syncModelValue();
      }
    },
    /**
     * 检测是否可以转为number
     * @param value
     * @returns {boolean}
     */
    canConvertToNumber(value) {
      return !isNaN(Number(value)) && value !== null && value !== '';
    },
    /** 同步当前值到v-model */
    syncModelValue() {
      const validValue = this.tagList.includes(this.modelValue)
          ? this.modelValue
          : this.tagList[this.currentTagIndex];
      this.currentTagIndex = this.tagList.findIndex(x => x === validValue);
      this.$emit('update:modelValue', validValue);
    },
    /**
     * 切换菜单
     * @param e
     */
    handleTabChange(e) {
      this.currentTagIndex = e.currentIndex;
      const selectedValue = this.tagList[this.currentTagIndex];
      // 关键修复5：切换时同步更新v-model
      this.$emit('update:modelValue', selectedValue);
      this.$emit('clickItem', {
        value: this.currentTagIndex,
        name: selectedValue
      });
    },
    async initDictData(dictCode) {
      let dictOptions = []
      //优先从缓存中读取字典配置
      if (this.getDictItemsFromCache(dictCode)) {
        dictOptions = this.getDictItemsFromCache(dictCode);
        if (dictOptions.length > 0) {
          return dictOptions
        }
      }
      //根据字典Code, 初始化字典数组
      let res = await getAction(this.url.root, {parentId: 'null', classifyType: this.code})
      if (res.success) {
        dictOptions = res.result.records.map(item => item.classifyName);
        //增加缓存
        uni.setStorage({key: dictCode, data: dictOptions});
      }
      return dictOptions
    },
    getDictItemsFromCache(dictCode) {
      try {
        const dictItems = uni.getStorageSync(dictCode);
        if (dictItems) {
          return dictItems;
        }
      } catch (e) {
        return null
      }
    }
  }
}
</script>
<style scoped lang="scss">

</style>